package com.yunquan.ohana.ui.editProfile.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatDialog
import androidx.databinding.DataBindingUtil
import com.yunquan.ohana.R
import com.yunquan.ohana.databinding.DialogNicknameBinding
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils

class NicknameDialog(context: Context) : AppCompatDialog(context) {
    private lateinit var binding: DialogNicknameBinding

    private var nickname: String? = null

    private var onInputListener: ((String) -> Unit)? = null

    fun setOnInputListener(listener: (String) -> Unit) {
        this.onInputListener = listener
    }

    fun setNickname(text: String) {
        this.nickname = text
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_nickname, null, false)
        setContentView(binding.root)
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setGravity(Gravity.CENTER)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        binding.etNickname.setText(nickname ?: "")
        binding.tvCount.text = "${binding.etNickname.text.length}/10"
        binding.etNickname.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                binding.tvCount.text = "${s?.length ?: 0}/10"
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })
        binding.btnCancel.setOnClickListener { dismiss() }
        binding.btnClear.setOnClickListener { binding.etNickname.text.clear() }
        binding.btnOk.setOnClickListener {
            val input = binding.etNickname.text.toString()
            if (StringUtils.isEmpty(input)) {
                ToastUtils.showShort(context.getString(R.string.please_enter_a_nickname))
            }
            onInputListener?.invoke(input)
            dismiss()
        }
    }
}